package gonz.grabber.modernbag;

import gonz.common.config.GrabLink;
import gonz.grabber.Grabber;
import gonz.grabber.Item;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;

import javax.json.Json;
import javax.json.stream.JsonParser;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class VKalbumGrabber extends Grabber {
    public static final String API_URL = "https://api.vk.com/method/";
    public static final String GET_PHOTO_METHOD = "photos.get?";
    public static final String API_VERSION = "v=5.5";
    private static final Logger LOGGER = Logger.getLogger(VKalbumGrabber.class);
    private static final List<String> IMG_KEYS = new ArrayList<String>() {{
        add("photo_75");
        add("photo_130");
        add("photo_604");
        add("photo_807");
        add("photo_1280");
        add("photo_2560");
    }};

    @Override
    protected List<Item> grabItems(WebDriver webDriver, GrabLink grabLink) {
        String albumLink = grabLink.getLink();
        String ownerAndAlbumIds = StringUtils.substringAfterLast(albumLink, "album");
        String ownerId = StringUtils.substringBefore(ownerAndAlbumIds, "_");
        String albumId = StringUtils.substringAfter(ownerAndAlbumIds, "_");
        String albumURL = API_URL + GET_PHOTO_METHOD + API_VERSION +
                "&" + "owner_id=" + ownerId + "&album_id=" + albumId + "&rev=1";
        List<Item> items = new ArrayList<Item>();
        try {
            URL url = new URL(albumURL);
            InputStream inputStream = url.openStream();
            JsonParser jsonParser = Json.createParser(inputStream);
            int imgCounter = 0;
            Map<String, String> imgLinksMap = new HashMap<String, String>();
            while (jsonParser.hasNext()) {
                JsonParser.Event event = jsonParser.next();
                switch (event) {
                    case START_ARRAY:
//                        LOGGER.debug("START_ARRAY");
                        break;
                    case START_OBJECT:
//                        LOGGER.debug("START_OBJECT");
                        break;
                    case KEY_NAME:
                        String keyName = jsonParser.getString();
                        if ("response".equals(keyName)) {
                            LOGGER.info("Response received.");
                        } else if ("count".equals(keyName)) {
                            jsonParser.next();
                            LOGGER.info("Images count:" + jsonParser.getString());
                        } else if ("id".equals(keyName)) {
                            imgCounter++;
                            jsonParser.next();
                            String imgId = jsonParser.getString();
                            String fullImgId = "photo" + ownerId + "_" + imgId;
                            String itemLink = "https://vk.com/" + fullImgId;

                            if (items.size() > 0) {
                                String prevImgLink = getBiggestImgLink(imgLinksMap);
                                Item prevItem = items.get(items.size() - 1);
                                List<String> prevImgLinks = prevItem.getImgLinks();
                                prevImgLinks.add(prevImgLink);
                                prevItem.setImgLinks(prevImgLinks);
                                imgLinksMap.clear();
                            }
                            Item item = new Item(String.valueOf(imgCounter), fullImgId, itemLink);
                            List<String> imgLinks = new ArrayList<String>();
                            item.setImgLinks(imgLinks);
                            items.add(item);
                        } else if (IMG_KEYS.contains(keyName)) {
                            jsonParser.next();
                            imgLinksMap.put(keyName, jsonParser.getString());
//                            LOGGER.debug(keyName + ":" + jsonParser.getString());
                        }
                        break;
                    case VALUE_STRING:
//                        LOGGER.debug("VALUE_STRING:" + jsonParser.getString());

                        break;
                    case VALUE_NUMBER:
//                        LOGGER.debug("VALUE_NUMBER:" + jsonParser.getString());

                        break;
                    case VALUE_TRUE:
//                        LOGGER.debug("VALUE_TRUE:" + jsonParser.getString());

                        break;
                    case VALUE_FALSE:
//                        LOGGER.debug("VALUE_FALSE:" + jsonParser.getString());

                        break;
                    case VALUE_NULL:
//                        LOGGER.debug("VALUE_NULL:" + jsonParser.getString());

                        break;
                    case END_OBJECT:
//                        LOGGER.debug("END_OBJECT");

                        break;
                    case END_ARRAY:
//                        LOGGER.debug("END_ARRAY");

                        break;
                }

            }


        } catch (MalformedURLException e) {
            LOGGER.error("Can't get VK album :" + albumURL + " " + grabLink, e);
        } catch (IOException e) {
            LOGGER.error("Can't open stream to VK album :" + albumURL + " " + grabLink, e);
        }
        return items;
    }

    private String getBiggestImgLink(Map<String, String> imgMap) {
        String result = null;
        for (String imgKey : IMG_KEYS) {
            if (imgMap.get(imgKey) == null) {
                return result;
            }
            result = imgMap.get(imgKey);
        }
        return result;
    }
}
